package com.wr.hangzhounewlight.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.f4b6a3.uuid.UuidCreator;
import com.wr.hangzhounewlight.mapper.DeviceMapper;
import com.wr.hangzhounewlight.mapper.OrderMapper;
import com.wr.hangzhounewlight.mapper.RecipeMapper;
import com.wr.hangzhounewlight.obj.api.recipesissue.RecipeIssueRequest;
import com.wr.hangzhounewlight.obj.api.recipesissue.RecipeIssueRequest.SiloSetDTO;
import com.wr.hangzhounewlight.obj.api.recipesissue.RecipeIssueResponse;
import com.wr.hangzhounewlight.obj.database.DeviceEntity;
import com.wr.hangzhounewlight.obj.database.OrderEntity;
import com.wr.hangzhounewlight.obj.database.RecipeEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author yuanzhizhuo
 * createDate 2025/10/23
 */
@Slf4j
@Service
public class RecipeIssueService {

    private final DeviceMapper deviceMapper;
    private final OrderMapper orderMapper;
    private final RecipeMapper recipeMapper;

    public RecipeIssueService(DeviceMapper deviceMapper, OrderMapper orderMapper, RecipeMapper recipeMapper) {
        this.deviceMapper = deviceMapper;
        this.orderMapper = orderMapper;
        this.recipeMapper = recipeMapper;
    }

    /**
     * 配方下发
     *
     * @param request dto
     * @return 是否下发成功
     */
    public RecipeIssueResponse recipeIssue(RecipeIssueRequest request) {
        try {
            saveToDB(request);
            log.info(
                    "配方下发, 车间: {}, 机台: {}, 螺杆: {}, 组合单号: {}已保存到数据库",
                    request.getWorkshop(), request.getMachine(), request.getScrew(), request.getOrderNo()
            );
        } catch (RuntimeException e) {
            log.error(
                    "配方下发, 车间: {}, 机台: {}, 螺杆: {}, 组合单号: {}保存到数据库失败",
                    request.getWorkshop(), request.getMachine(), request.getScrew(), request.getOrderNo(), e
            );
            return new RecipeIssueResponse(0, "保存到数据库失败");
        }
        return new RecipeIssueResponse(1, "配方下发成功");
    }

    /**
     * 保存配方到数据库
     *
     * @param request dto
     * @throws RuntimeException 保存到数据库失败
     */
    private void saveToDB(RecipeIssueRequest request) throws RuntimeException {
        String deviceId = UuidCreator.getTimeOrdered().toString();
        int deviceInsertIgnore = deviceMapper.insertIgnore(deviceId, request.getWorkshop(), request.getMachine(), request.getScrew());
        if (deviceInsertIgnore == 0) {
            LambdaQueryWrapper<DeviceEntity> queryWrapper = new LambdaQueryWrapper<DeviceEntity>()
                    .eq(DeviceEntity::getWorkshop, request.getWorkshop())
                    .eq(DeviceEntity::getMachine, request.getMachine())
                    .eq(DeviceEntity::getScrew, request.getScrew());
            deviceId = deviceMapper.selectOne(queryWrapper).getId();
        }
        String orderNo = request.getOrderNo();
        String orderId = UuidCreator.getTimeOrdered().toString();
        int orderInsertIgnore = orderMapper.insertIgnore(orderId, deviceId, orderNo);
        if (orderInsertIgnore == 0) {
            LambdaQueryWrapper<OrderEntity> queryWrapper = new LambdaQueryWrapper<OrderEntity>()
                    .select(OrderEntity::getId)
                    .eq(OrderEntity::getOrderNo, orderNo);
            orderId = orderMapper.selectOne(queryWrapper).getId();
            resetOrderNoRecipes(orderId, orderNo);
        }
        for (SiloSetDTO siloSetDTO : request.getSiloSet()) {
            recipeMapper.insert(new RecipeEntity(orderId, siloSetDTO.getSilo(), siloSetDTO.getRatio()));
        }
    }

    /**
     * 重置组合单号的配方比例
     *
     * @param orderId 订单id
     * @param orderNo 组合单号
     */
    private void resetOrderNoRecipes(String orderId, String orderNo) {
        log.info("配方下发, 正在重置组合单号: {}的配方比例", orderNo);
        LambdaUpdateWrapper<RecipeEntity> updateWrapper = new LambdaUpdateWrapper<RecipeEntity>()
                .eq(RecipeEntity::getOrderId, orderId);
        recipeMapper.delete(updateWrapper);
    }

}
